package com.simba.server.commands.impl.web;

import com.google.gson.Gson;
import com.simba.common.command.ICommand;
import com.simba.server.base.CommonUtil;
import com.simba.server.base.TimeUtil;
import com.simba.server.components.MachineParams;
import com.simba.server.components.SorterParams;
import com.simba.server.components.data.ResultBase;
import com.simba.server.components.data.ResultInfo;
import com.simba.server.components.data.ResultSlot;
import org.apache.log4j.Logger;

import com.simba.common.log.LogUtil;
import com.simba.server.ServerParam;
import com.simba.server.components.data.SortInfo;
import com.simba.server.webservice.WebServiceManager;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 落格信息回传
 *
 * @return success or error
 */
public class WebPacketOffCmd implements ICommand
{
	public static final String NAME = "WebPacketOffCmd";
	private static final Logger logger = Logger.getLogger(WebPacketOffCmd.class);
	private final SortInfo sort;

	public WebPacketOffCmd(SortInfo sort)
	{
		this.sort = sort;
	}

	@Override
	public String getName()
	{
		return WebPacketOffCmd.NAME;
	}

	@Override
	public Boolean run(Object params)
	{
		boolean ret = false;
		String remoteMethod = "AutoSort/DropChute";

		Map<String,Object> rp = new HashMap<>();
		//唯一标识，必须要等于分拣接口的GUID
		rp.put("Guid", this.sort.getSortingId());
		//分拣机代码，可不填
		rp.put("MachineCode", MachineParams.getInstance().getDeviceId());
		//格口号
		rp.put("ChuteCode",this.sort.getDroppedSlotId());
		//圈数
		rp.put("TurnNumber",this.sort.getTurnNumber());
		//落格时间
		rp.put("PacketOffTime",this.sort.getTimePacketOff());
		//上件时间
		rp.put("PacketOnTime",this.sort.getTimePacketOn());
		//请求时间
		rp.put("RequestTime", TimeUtil.getTimeDateString("yyyy-MM-dd HH:mm:ss", new Date()));

		Gson gson = CommonUtil.getGson();
		String content = gson.toJson(rp);

		try
		{
			if (SorterParams.getInstance().isDebugMode()){
				LogUtil.LogError(logger, "upload package off error: debug mode doesn't upload data!");
				return false;
			}

			ResultInfo response = WebServiceManager.getInstance().doHttpServiceByPost(
					ServerParam.REMOTE_WEBSERVICE_ADDRESS, remoteMethod, content);
			if (response != null && response.getCode() >= 200 && response.getCode() < 202)
			{
				ret = this.handleResponse(response);
			}
		}
		catch (Exception e)
		{
			LogUtil.LogError(WebPacketOffCmd.logger, "upload package off error: " + e);
			ret = false;

		}
		return ret;
	}

	private boolean handleResponse(ResultInfo response)
	{
		boolean ret = false;
		try
		{
			ResultBase result = CommonUtil.getGson().fromJson(response.getData(), ResultBase.class);
			if (result.getCode() == 200){
				ret = true;
			}
		}
		catch (Exception e)
		{
			LogUtil.LogError(WebPacketOffCmd.logger, "parse package off result failed : " + e);
		}
		return ret;
	}
}
